<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0,user-scalable=no,shrink-to-fit=yes">
 
    <title>山东抗日战争纪念馆 v2.4.22</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
	<!-- Favicon for modern browsers (PNG) -->
	<link rel="icon" type="image/png" sizes="16x16" href="TemplateData/favicon-16x16.png">
	<link rel="icon" type="image/png" sizes="32x32" href="TemplateData/favicon-32x32.png">

	<!-- Apple Touch Icon for iOS devices -->
	<link rel="apple-touch-icon" sizes="180x180" href="TemplateData/apple-touch-icon.png">

	<!-- Android Chrome icons -->
	<link rel="icon" type="image/png" sizes="192x192" href="TemplateData/android-chrome-192x192.png">
	<link rel="icon" type="image/png" sizes="512x512" href="TemplateData/android-chrome-512x512.png">

	<!-- Link to the Web App Manifest -->
	<!-- 确保 site.webmanifest 文件位于网站的根目录 -->
	<link rel="manifest" href="site.webmanifest">

    <link rel="stylesheet" href="TemplateData/style.css">

	<style>
	  /* 预览遮罩与图片（支持微信长按） */
	  #preview-mask{
		position:fixed;inset:0;background:rgba(0,0,0,.6);
		display:none;align-items:center;justify-content:center;z-index:999;
		padding: env(safe-area-inset-top, 0px) 16px env(safe-area-inset-bottom, 0px) 16px; /* 兼容刘海屏 */
	  }
	  #preview-wrap{
		position:relative;
		max-width:84vw;  /* 原 92 → 84，更小 */
		max-height:82vh; /* 原 92 → 82，留出上下空间 */
	  }
	  #preview{
		max-width:84vw;
		max-height:72vh; /* 预留给底部文案的空间 */
		border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,.6);
		object-fit:contain;
	  }
	  #preview-tip{
		margin-top:10px;
		color:#fff;font-size:14px;font-family:sans-serif;text-align:center;opacity:.9;
	  }
	  #preview-close{
		position:fixed;top:14px;right:14px;width:36px;height:36px;border-radius:18px;
		background:rgba(255,255,255,.15);color:#fff;border:none;font-size:20px;line-height:36px;text-align:center;
	  }
	  /* 横屏下进一步缩小并上移，避免被微信顶部栏压住 */
	  @media (orientation: landscape){
		#preview-wrap{
		  max-width:80vw;
		  max-height:70vh;
		  transform: translateY(-4vh); /* 稍微上移一点，避开顶部栏+地址栏 */
		}
		#preview{
		  max-width:80vw;
		  max-height:60vh;
		}
		#preview-tip{ font-size:13px; }
	  }
	</style>
  </head>
  <body>
  <!-- 预览遮罩（用于长按保存/发送） -->
  <div id="preview-mask" role="dialog" aria-label="分享预览">
    <button id="preview-close" aria-label="关闭">×</button>
    <div id="preview-wrap">
      <img id="preview" alt="长按图片可保存或发送给朋友">
      <div id="preview-tip">长按图片可保存到相册或发送给朋友</div>
    </div>
  </div>
    <div id="unity-container" class="unity-desktop">
      <canvas id="unity-canvas" width=960 height=540 tabindex="-1"></canvas>
      <div id="unity-loading-bar">
        <div id="unity-logo"></div>
        <div id="unity-progress-bar-empty">
          <div id="unity-progress-bar-full"></div>
        </div>
      </div>
      <div id="unity-warning"> </div>
      <div id="unity-footer">
        <div id="unity-logo-title-footer"></div>
        <div id="unity-fullscreen-button"></div>
        <div id="unity-build-title">
			<img src="TemplateData/title.jpg" alt="山东抗日战争纪念馆">
		</div>
      </div>
    </div>
    
    
    <script>
	    window.FinalShot = '';

    // Unity 回调：截图已就绪 → 显示预览层
	document.addEventListener('unity_shot_ready', () => {
	  if (!window.FinalShot) return;
	  const mask = document.getElementById('preview-mask');
	  const img  = document.getElementById('preview');
	  img.src = window.FinalShot;
	  mask.style.display = 'flex';
	});

	// 关闭预览
	document.getElementById('preview-close').addEventListener('click', () => {
	  const mask = document.getElementById('preview-mask');
	  const img  = document.getElementById('preview');
	  img.src = '';
	  mask.style.display = 'none';
	});
	// 点击遮罩空白关闭
	document.getElementById('preview-mask').addEventListener('click', (e) => {
	  if (e.target.id === 'preview-mask') {
		document.getElementById('preview-close').click();
	  }
	});

	/* Unity Loader（保留你的现有逻辑） */
      // Shows a temporary message banner/ribbon for a few seconds, or
      // a permanent error message on top of the canvas if type=='error'.
      // If type=='warning', a yellow highlight color is used.
      // Modify or remove this function to customize the visually presented
      // way that non-critical warnings and error messages are presented to the
      // user.
      function unityShowBanner(msg, type) {
        var warningBanner = document.querySelector("#unity-warning");
        function updateBannerVisibility() {
          warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
        }
        var div = document.createElement('div');
        div.innerHTML = msg;
        warningBanner.appendChild(div);
        if (type == 'error') div.style = 'background: red; padding: 10px;';
        else {
          if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
          setTimeout(function() {
            warningBanner.removeChild(div);
            updateBannerVisibility();
          }, 5000);
        }
        updateBannerVisibility();
      }

      var canvas = document.querySelector("#unity-canvas");

      var buildUrl = "Build";
      var loaderUrl = buildUrl + "/webgl202508252317_2.4.22Release.loader.js";
      var config = {
        arguments: [],
        dataUrl: buildUrl + "/webgl202508252317_2.4.22Release.data",
        frameworkUrl: buildUrl + "/webgl202508252317_2.4.22Release.framework.js",
        codeUrl: buildUrl + "/webgl202508252317_2.4.22Release.wasm",
        streamingAssetsUrl: "StreamingAssets",
        companyName: "sdkrzzjng",
        productName: "山东抗日战争纪念馆",
        productVersion: "2.4.22",
        showBanner: unityShowBanner,
      };

      // By default, Unity keeps WebGL canvas render target size matched with
      // the DOM size of the canvas element (scaled by window.devicePixelRatio)
      // Set this to false if you want to decouple this synchronization from
      // happening inside the engine, and you would instead like to size up
      // the canvas DOM size and WebGL render target sizes yourself.
      // config.matchWebGLToCanvasSize = false;

      // If you would like all file writes inside Unity Application.persistentDataPath
      // directory to automatically persist so that the contents are remembered when
      // the user revisits the site the next time, uncomment the following line:
      // config.autoSyncPersistentDataPath = true;
      // This autosyncing is currently not the default behavior to avoid regressing
      // existing user projects that might rely on the earlier manual
      // JS_FileSystem_Sync() behavior, but in future Unity version, this will be
      // expected to change.

      if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
        // Mobile device style: fill the whole browser client area with the game canvas:

        var meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
        document.getElementsByTagName('head')[0].appendChild(meta);
        document.querySelector("#unity-container").className = "unity-mobile";
        canvas.className = "unity-mobile";

        // To lower canvas resolution on mobile devices to gain some
        // performance, uncomment the following line:
        // config.devicePixelRatio = 1;


      } else {
        // Desktop style: Render the game canvas in a window that can be maximized to fullscreen:
        canvas.style.width = "960px";
        canvas.style.height = "540px";
         // Desktop: canvas follows CSS (100%)
         //  canvas.style.width  = "100%";
         //  canvas.style.height = "100%";
      }

      document.querySelector("#unity-loading-bar").style.display = "block";

	  // ========= 随机背景（开始）=========
      // 横屏（PC 与手机横屏）
      const H_BG_IMAGES = [
        'TemplateData/HBg/AI.jpg',
        'TemplateData/HBg/BXT.jpg',
        'TemplateData/HBg/CCT.jpg',
        'TemplateData/HBg/GJD.jpg',
        'TemplateData/HBg/kG.jpg',
        'TemplateData/HBg/KSK.jpg',
        'TemplateData/HBg/LCT.jpg',
        'TemplateData/HBg/SW.jpg',
        'TemplateData/HBg/WZDZ.jpg',
        'TemplateData/HBg/XT.jpg',
        'TemplateData/HBg/YLT.jpg',
        'TemplateData/HBg/YYZDT.jpg'
      ];
      // 竖屏（仅手机浏览器竖屏）
      // 注意：目录应为 VBg（请确保这些文件真实存在）
      const V_BG_IMAGES = [
        'TemplateData/VBg/AI.jpg',
        'TemplateData/VBg/BXT.jpg',
        'TemplateData/VBg/CCT.jpg',
        'TemplateData/VBg/GJD.jpg',
        'TemplateData/VBg/kG.jpg',
        'TemplateData/VBg/KSK.jpg',
        'TemplateData/VBg/LCT.jpg',
        'TemplateData/VBg/SW.jpg',
        'TemplateData/VBg/WZDZ.jpg',
        'TemplateData/VBg/XT.jpg',
        'TemplateData/VBg/YLT.jpg',
        'TemplateData/VBg/YYZDT.jpg'
      ];

      function pickRandom(arr) {
        return arr[Math.floor(Math.random() * arr.length)];
      }

      function idlePreload(url) {
        const preload = () => { const img = new Image(); img.src = url; };
        if ('requestIdleCallback' in window) requestIdleCallback(preload, { timeout: 2000 });
        else setTimeout(preload, 0);
      }

      let applyBgDebounce;
      function applyRandomBg() {
        // 简单防抖，避免连续 resize 触发多次加载
        clearTimeout(applyBgDebounce);
        applyBgDebounce = setTimeout(() => {
          console.log('[BG] run');
          const isPortrait = window.matchMedia('(orientation: portrait)').matches;
          const isMobile = document.querySelector('#unity-container').classList.contains('unity-mobile');
          const list = (isMobile && isPortrait) ? V_BG_IMAGES : H_BG_IMAGES;
          const otherList = (isMobile && isPortrait) ? H_BG_IMAGES : V_BG_IMAGES;

          if (!list.length) {
            console.warn('[BG] image list empty');
            return;
          }
          const url = pickRandom(list);
          const c = document.querySelector('#unity-canvas');
          // 设定背景图与常用属性，避免被外部样式影响
          c.style.backgroundImage = `url('${url}')`;
          c.style.backgroundSize = 'cover';
          c.style.backgroundRepeat = 'no-repeat';
          c.style.backgroundPosition = 'center';
          console.log('[BG] isMobile=', isMobile, 'isPortrait=', isPortrait, 'picked=', url);

          // 闲时预加载“对向”一张，减少旋转时白屏
          if (otherList.length) idlePreload(pickRandom(otherList));
        }, 150);
      }

      // 初次设置 + 绑定事件
      applyRandomBg();
      window.addEventListener('orientationchange', applyRandomBg);
      window.addEventListener('resize', applyRandomBg);
      // ========= 随机背景（结束）=========

      var script = document.createElement("script");
      script.src = loaderUrl;
      script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          document.querySelector("#unity-progress-bar-full").style.width = 100 * progress + "%";
              }).then((unityInstance) => {
                document.querySelector("#unity-loading-bar").style.display = "none";
                document.querySelector("#unity-fullscreen-button").onclick = () => {
                  document.makeFullscreen('unity-container');
                };

              }).catch((message) => {
                alert(message);
              });
            };

      document.body.appendChild(script);

    </script>
  </body>
</html>
